import React, { useEffect, useRef } from 'react'
import * as echarts from 'echarts'
import type { EChartsOption } from 'echarts'

interface BarChartProps {
  data: {
    xAxis: string[]
    series: Array<{
      name: string
      data: number[]
    }>
  }
  title?: string
  loading?: boolean
  height?: number
  style?: React.CSSProperties
}

const BarChart: React.FC<BarChartProps> = ({
  data,
  title,
  loading,
  height = 400,
  style
}) => {
  const chartRef = useRef<HTMLDivElement>(null)
  const chartInstance = useRef<echarts.ECharts>()

  useEffect(() => {
    if (!chartRef.current) return

    chartInstance.current = echarts.init(chartRef.current)

    const option: EChartsOption = {
      title: title ? { text: title } : undefined,
      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'shadow'
        }
      },
      legend: {
        data: data.series.map(item => item.name)
      },
      xAxis: {
        type: 'category',
        data: data.xAxis
      },
      yAxis: {
        type: 'value'
      },
      series: data.series.map(item => ({
        name: item.name,
        data: item.data,
        type: 'bar'
      })),
      loading
    }

    chartInstance.current.setOption(option)

    return () => {
      chartInstance.current?.dispose()
    }
  }, [data, title, loading])

  useEffect(() => {
    const handleResize = () => {
      chartInstance.current?.resize()
    }

    window.addEventListener('resize', handleResize)
    return () => window.removeEventListener('resize', handleResize)
  }, [])

  return (
    <div 
      ref={chartRef} 
      style={{ height, ...style }}
    />
  )
}

export default BarChart 